package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("login")
    public R login(HttpServletRequest request, @RequestBody Employee employee) {
        //①. 将页面提交的密码password进行md5加密处理, 得到加密后的字符串  DigestUtils工具类
        String mdPassword = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        //②. 根据页面提交的用户名username查询数据库中员工数据信息
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee employeeDb = employeeService.getOne(lqw);
        //③. 如果没有查询到, 则返回登录失败结果
        if (employeeDb == null) {
            return R.error("用户名或密码错误");
        }
        //④. 密码比对，如果不一致, 则返回登录失败结果
        if (!mdPassword.equals(employeeDb.getPassword())) {
            return R.error("用户名或密码错误");
        }
        //⑤. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (employeeDb.getStatus() == 0) {
            return R.error("员工已禁用");
        }
        //⑥. 登录成功，将员工id存入Session, 并返回登录成功结果
        request.getSession().setAttribute("employee",employeeDb.getId());
        return R.success(employeeDb);
    } //登录

    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("登出成功");
    } //登出

    @PostMapping
    @CacheEvict(cacheNames = "employee",allEntries = true)
    public R save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("添加员工:{}",employee);
        //设置初始密码123456，需要进行md5加密处理DigestUtils,记得用set方法把密码传入
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
    /*    // 获得当前时间,set到 创建时间和修改时间
        LocalDateTime now = LocalDateTime.now();
        employee.setCreateTime(now);
        employee.setUpdateTime(now);
        //获得当前登录用户的id,set到 创建人和最后修改人
        Long id = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(id);
        employee.setUpdateUser(id);*/
        // 调用方法添加对象
        employeeService.save(employee);
        return R.success("新增员工成功");
    } //增

    @GetMapping("page")
    @Cacheable(cacheNames = "employee",key = "#page+'_'+#pageSize+'_'+#name")
    public R page(Integer page, Integer pageSize, String name) {
        IPage<Employee> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(name), Employee::getName, name);
        lqw.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo,lqw);
        return R.success(pageInfo);
    } // 分页+动态条件查

    @GetMapping("/{id}")
    @Cacheable(cacheNames = "employee",key = "#id")
    public R getById(@PathVariable Long id) {
        log.info("需要查询的id是:{}", id);

        Employee empById = employeeService.getById(id);
        if (empById != null) {
            return R.success(empById);
        }

        return R.error("没有这个人");
    } // 根据id查

    @PutMapping
    @CacheEvict(cacheNames = "employee",allEntries = true)
    public R update(HttpServletRequest request, @RequestBody Employee employee) {
        log.info(employee.toString());
        // 设置修改时间和修改人
/*        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        employee.setUpdateTime(LocalDateTime.now());*/
        employeeService.updateById(employee);
        return R.success("修改完成");
    } //改

} 